package com.cdn.website.service.impl;

import com.cdn.website.service.NginxConfigService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
public class NginxConfigServiceImpl implements NginxConfigService {

    @Override
    public String generateNginxConfig(List<String> domains, String originAddress, List<Integer> ports) {
        StringBuilder nginxConfig = new StringBuilder();

        // 遍历每个域名
        for (String domain : domains) {
            // 遍历每个端口
            for (int port : ports) {
                String nginxConfigTemplate =
                        "server {\n" +
                                "    listen %d;\n" +
                                "    server_name %s;\n" +
                                "\n" +
                                "    location / {\n" +
                                "        proxy_pass %s;\n" +
                                "        proxy_set_header Host $host;\n" +
                                "        proxy_set_header X-Real-IP $remote_addr;\n" +
                                "        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "        proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "    }\n" +
                                "}\n";

                // 将域名和端口填充到模板中
                nginxConfig.append(String.format(nginxConfigTemplate, port, domain, originAddress, port));
            }
        }

        return nginxConfig.toString();
    }

    @Override
    public boolean writeConfigToFile(String config, String path) {
        try {
            // 写入配置文件到 Nginx 配置目录
            Files.write(Paths.get(path), config.getBytes(StandardCharsets.UTF_8));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
